<?php
/*********************************************************************************
* Filename: team_home.php
* 
* This page provides the team owner an interface to manage their team's roster, and
* view stats for both their players, and their upcoming opponent's players.
*
* Author: Phillip Peterson
* Date Created: 09/15/2009
**********************************************************************************/

//Start the PHP session is it doesn't exist
if (!isset($_SESSION))
	session_start();
//Check if the team is logged in.  If not, redirect the user
//to the login page.

if (!isset($_SESSION['team_id'])){
	include_once "common.php";
	$path = $g_server . $g_login_page;

	header("Location: $path");
	die();
}


//The common.php file contains 
include_once "common.php";

//Get the team id from the global session and echo the HTML header infotmation
$team_id = $_SESSION['team_id'];

echo "$header_open";
echo "$css_team_home";
echo "$js_team_home";
echo "$header_close";
?>

<?php 
    $query = "SELECT * FROM TEAMS WHERE TEAM_ID = $team_id";
    $results = do_query($query, $g_db_name, $g_username);
    $row = mysql_fetch_assoc($results);
    $the_league = $row['LEAGUE_ID'];
    
    $query = "SELECT * FROM LEAGUES WHERE LEAGUE_ID = $the_league";
    $results = do_query($query, $g_db_name, $g_username);
    $row = mysql_fetch_assoc($results);
    $draft_done = $row['DRAFT_DONE'];
    $scheduled = $row['SCHEDULED'];
    
   	//Query to get the current week for the league
	$query = "SELECT WEEK
			  FROM GAMES
			  WHERE ISNULL(TEAM_1_SCORE)";
	$results = do_query($query, $g_db_name, $g_username);       
       
    if (!$draft_done) {
	    $path = $g_server . $g_nodraft_page;
    	header("Location: $path");
    	die();
    }
    else if (!$scheduled) {
        $path = $g_server . $g_noschedule_page;
    	header("Location: $path");
    	die();
    } 
    //Check if the all league games have been played, if so
    //forward the user to the champ page
    else if (mysql_num_rows($results) == 0){
        $path = $g_server . $g_champ;
	    header("Location: $path");
	    die();
    }    
    else {
?>

<body onload="postLoad();" onclick="checkPosition(event);">
	<div id="wrapper">
		<div id="inner">
			<?php
				echo "$g_nav_div";
			?>
			<div id="rink">
			<?php

				include_once "common.php";
				
				$query = "SELECT DRAFT_DONE FROM LEAGUES WHERE LEAGUE_ID = {$_SESSION['league_id']}";
				$result = do_query($query,$g_db_name,$g_username);
				$row = mysql_fetch_assoc($result);

				if ($row['DRAFT_DONE'] != 1){
						//Get the current week number, store as javascript variable
						echo "<script type='text/javascript'> var g_cur_week = 1;</script>";
						echo "<script type='text/javascript'> var g_team_id  = $team_id;</script>"; 

						echo "<div id='no_draft_mess'>Your league has not drafted player yet</div>";

				}
				else {

						$ice_players     = array();
						$ice_player_id   = array();
						$bench_players   = array();
						$bench_player_id = array();

						$query = "SELECT r.PLAYER_ID, r.POSITION, p.PLAYER_NAME
								  FROM ROSTER r
								  LEFT OUTER JOIN PLAYERS p
								  ON p.PLAYER_ID = r.PLAYER_ID
								  WHERE r.TEAM_ID = $team_id";

						$results = do_query($query, $g_db_name, $g_username);
						$player_name = array();
						$player_id = array();
						$position = array();

						while($row = mysql_fetch_assoc($results)){
							$player_name[] = $row['PLAYER_NAME'];
							$position[]    = $row['POSITION'];
							$player_id[]   = $row['PLAYER_ID'];
						}

						for ($i = 0; $i < sizeof($player_name); $i++){
							if ($position[$i] == 1){
								$ice_players[]   = $player_name[$i];
								$ice_player_id[] = $player_id[$i];
							}
							else{
								$bench_players[]   = $player_name[$i];
								$bench_player_id[] = $player_id[$i];
							}
						}

						//Echo each player on the ice
						for ($i = 0; $i < 6; $i++){
							$id  = "home_player_";
							$id .= ($i+1);
							echo "<img id=$id src='images/rink/red_player.png' alt='{$ice_players[$i]}' name='{$ice_player_id[$i]}'
									   onmouseover='hoverIcePlayer(this);' onmouseout='unhoverIcePlayers(this);'>";
							$id .= "_label";
							$temp = explode(" ",$ice_players[$i]);
							$label = $temp[0][0] . ". " . $temp[1];
							echo "<span class='textLabel_home' id=$id >$label </span>";
						}

						for ($i = 0; $i < 4; $i++){
							$id  = "home_bench_";
							$id .= ($i+1);
							echo "<img id=$id src='images/rink/red_player.png' alt='{$bench_players[$i]}' name='{$bench_player_id[$i]}'>";
							$id .= "_label";
							$temp = explode(" ",$bench_players[$i]);
							$label = $temp[0][0] . ". " . $temp[1];
							echo "<span class='textLabel_home' id=$id >$label </span>";

						}
						
						//Query to get the current week for the league
						$query = "SELECT WEEK
								  FROM GAMES
								  WHERE ISNULL(TEAM_1_SCORE)
								  ORDER BY WEEK ASC LIMIT 1";
                        //AND (TEAM1=$team_id OR TEAM2=$team_id) ORDER BY WEEK ASC LIMIT 1";
						$results = do_query($query, $g_db_name, $g_username);

						$row = mysql_fetch_assoc($results);
						$week = $row['WEEK'];
						
						$query = "SELECT TEAM1, TEAM2
						          FROM GAMES
						          WHERE WEEK = $week AND (TEAM1=$team_id OR TEAM2=$team_id)";
						          
						$results = do_query($query, $g_db_name, $g_username);
						$bye_week = 0;
						
						if (mysql_num_rows($results) == 0)
						    $bye_week = 1;
						else {				          
                            $row = mysql_fetch_assoc($results);					          
						
						    //Determine opposing team's ID
						    $opp_team_id = $row['TEAM1'];
						    if ($opp_team_id == $team_id) {
							    $opp_team_id = $row['TEAM2'];
						    }

						    //Get the roster information for the opposing team
						    $query = "SELECT r.PLAYER_ID, r.POSITION, p.PLAYER_NAME
								      FROM ROSTER r
								      LEFT OUTER JOIN PLAYERS p
								      ON p.PLAYER_ID = r.PLAYER_ID
								      WHERE r.TEAM_ID = $opp_team_id";

						    $results = do_query($query, $g_db_name, $g_username);
						
						    //Reinitialize the arrays used for setting up the players
						    $player_name   = array();
						    $position      = array();
						    $ice_players   = array();
						    $bench_players = array();

						    //Get the information for the opposing players
						    while($row = mysql_fetch_assoc($results)){
							    $player_name[] = $row['PLAYER_NAME'];
							    $position[]    = $row['POSITION'];
						    }
						
						    //Loop to setup the bench and ice player arrays for the opposing team
						    for ($i = 0; $i < sizeof($player_name); $i++){
							    if ($position[$i] == 1)
								    $ice_players[] = $player_name[$i];
							    else
								    $bench_players[] = $player_name[$i];
						    }

						    //Echo each player on the ice
						    for ($i = 0; $i < 6; $i++){
							    $id  = "away_player_";
							    $id .= ($i+1);
							    echo "<img id=$id src='images/rink/blue_player.png' alt='{$ice_players[$i]}'>";
							    $id .= "_label";
							    $temp = explode(" ",$ice_players[$i]);
							    $label = $temp[0][0] . ". " . $temp[1];
							    echo "<span class='textLabel_away' id=$id >$label </span>";
						    }

						    for ($i = 0; $i < 4; $i++){
							    $id  = "away_bench_";
							    $id .= ($i+1);
							    echo "<img id=$id src='images/rink/blue_player.png' alt='{$bench_players[$i]}'>";
							    $id .= "_label";
							    $temp = explode(" ",$bench_players[$i]);
							    $label = $temp[0][0] . ". " . $temp[1];
							    echo "<span class='textLabel_away' id=$id >$label </span>";
						    }
						
						    
						    $opp_team_name  = get_value("team_id",$opp_team_id);
						}
						$home_team_name = get_value("team_id",$team_id);
						
						if ($bye_week)
						    $opp_team_name = "Bye Week";
					    echo "<div id='rink_home_label' class='rink_label'>$home_team_name</div>";
   						echo "<div id='rink_opp_label' class='rink_label'>$opp_team_name</div>";

						//Get the current week number, store as javascript variable
						echo "<script type='text/javascript'> var g_cur_week = $week;</script>";
						echo "<script type='text/javascript'> var g_team_id  = $team_id;</script>"; 
						echo "<script type='text/javascript'> var g_team_name  = '$home_team_name';</script>";
					}

			?>
			</div>

			<div id="content">
				<div id="container-1">
					<ul class="ui-tabs-nav">
						<li class="ui-tabs-selected">
							<a href="#fragment-1">
								<span>Team Roster</span>
							</a>
						</li>
						<li class="">
							<a href="#fragment-2">
								<span>Opponent Roster</span>
							</a>
						</li>
						<li class="">
							<a href="#fragment-3">
								<span>Your Trades</span>
							</a>
						</li>
					</ul>

					<div id="fragment-1" class="ui-tabs-panel">
						<table class="expandable">
								<tr class="table_header">
									<td width=25></td>
									<td class="name_cell">Player</td>
									<td class="point_cell">Saves</td>
									<td class="point_cell">Assists</td>
									<td class="point_cell">Goals</td>
									<td class="point_cell">Fan Pts</td>
								</tr>
								<?php
									// The header query, which gathers the total statistical values for each player according on the given
									// team ID
									$header_query = 'SELECT p.PLAYER_ID, p.PLAYER_NAME, p.PLAYER_ISO, 
													 SUM(s.GOALS) as TOTAL_GOALS, SUM(s.ASSISTS) as TOTAL_ASSISTS, '
										 . 'SUM(s.SAVES) as TOTAL_SAVES, SUM(s.SCORE) as TOTAL_SCORE '
										 . 'FROM ROSTER r '
										 . 'LEFT OUTER JOIN PLAYERS p '
										 . 'ON p.PLAYER_ID = r.PLAYER_ID '
										 . 'LEFT OUTER JOIN STATS s '
											 . 'ON s.PLAYER_ID = r.PLAYER_ID '
										 . 'WHERE TEAM_ID = ' . $team_id . ' '
										 . 'GROUP BY p.PLAYER_ID '
										 . 'ORDER BY TOTAL_SCORE desc';

									$result = do_query($header_query, $g_db_name, $g_username);		

									$align = "align='center'";
									$i = 0;

									// Cycle through all the players are display their totals in a parent row
									while ($row = mysql_fetch_assoc($result)) {
										
										$shade         = (($i+1)%2) ? 'shade_odd' : 'shade_even';
										$name          = $row['PLAYER_NAME'];
										$player_iso    = $row['PLAYER_ISO'];
										$player_id     = $row['PLAYER_ID'];
										$total_goals   = $row['TOTAL_GOALS'];
										$total_assists = $row['TOTAL_ASSISTS'];
										$total_saves   = $row['TOTAL_SAVES'];
										$total_score   = $row['TOTAL_SCORE'];

										$broomball_link = 'http://www.broomball.mtu.edu/user/' . $player_iso;

										echo "<tr class=$shade onmouseover='rowHover(this);' onmouseout='rowUnHover(this);'>";
                                        $color = ($shade == "shade_odd") ? "#E0F0F9" : "#FFFFFF"; 
                                        echo "
											 <td $align class='table_arrow'>+</td>
											 <td><a class='bb_link' href='$broomball_link' target='_blank'>$name</a></td>
											 <td $align>$total_saves</td>
											 <td $align>$total_assists</td>
											 <td $align>$total_goals</td>
											 <td $align>$total_score</td>
										</tr>
										";
										
										// Grab all the individual weekly statistics for each player
										$child_query = 'SELECT WEEK, GOALS, ASSISTS, SAVES, SCORE 
                                                        FROM STATS 
                                                        WHERE PLAYER_ID = ' . $player_id. '
                                                        ORDER BY WEEK ASC';
										$child_result = do_query($child_query, $g_db_name, $g_username);
										$j = 0;

										// Cycle through all the weekly stats for an individual player and make them children rows
										// of the parent row
										while ($child_row = mysql_fetch_assoc($child_result)) {
											$j = $j + 1;
											$week_saves = $child_row['SAVES'];
											$week_assists = $child_row['ASSISTS'];
											$week_goals = $child_row['GOALS'];
											$week_score = $child_row['SCORE'];
											echo "<tr class=$shade>
													<td></td>
													<td>Week $j</td>
													<td $align>$week_saves</td>
													<td $align>$week_assists</td>
													<td $align>$week_goals</td>
													<td $align>$week_score</td>
												 </tr>
											";
										} 

										$i = $i + 1;
									}
								?>
							</table>
					</div>
					<div id="fragment-2" class="ui-tabs-panel ui-tabs-hide">
						<table class="expandable">
								<tr class="table_header">
									<td width=25></td>
									<td class="name_cell">Player</td>
									<td class="point_cell">Saves</td>
									<td class="point_cell">Assists</td>
									<td class="point_cell">Goals</td>
									<td class="point_cell">Fan Pts</td>
								</tr>
								<?php
								    if (!$bye_week){
									    // The header query, which gathers the total statistical values for each player according on the given
									    // team ID
									    $header_query = 'SELECT p.PLAYER_ID, p.PLAYER_NAME, SUM(s.GOALS) as TOTAL_GOALS, SUM(s.ASSISTS) as TOTAL_ASSISTS, '
										     . 'SUM(s.SAVES) as TOTAL_SAVES, SUM(s.SCORE) as TOTAL_SCORE '
										     . 'FROM ROSTER r '
										     . 'LEFT OUTER JOIN PLAYERS p '
										     . 'ON p.PLAYER_ID = r.PLAYER_ID '
										     . 'LEFT OUTER JOIN STATS s '
											     . 'ON s.PLAYER_ID = r.PLAYER_ID '
										     . 'WHERE TEAM_ID = ' . $opp_team_id . ' '
										     . 'GROUP BY p.PLAYER_ID '
										     . 'ORDER BY TOTAL_SCORE desc';

									    $result = do_query($header_query, $g_db_name, $g_username);		

									    $align = "align='center'";
									    $i = 0;

                                    
									    // Cycle through all the players are display their totals in a parent row
									    while ($row = mysql_fetch_assoc($result)) {
										
										    $shade = (($i+1)%2) ? 'shade_odd' : 'shade_even';
										    $name = $row['PLAYER_NAME'];
										    $player_id = $row['PLAYER_ID'];
										    $total_goals = $row['TOTAL_GOALS'];
										    $total_assists = $row['TOTAL_ASSISTS'];
										    $total_saves = $row['TOTAL_SAVES'];
										    $total_score = $row['TOTAL_SCORE'];

										    echo "<tr class=$shade onmouseover='rowHover(this);' onmouseout='rowUnHover(this);'>
											     <td $align class='table_arrow'>+</td>
											     <td>$name</td>
											     <td $align>$total_saves</td>
											     <td $align>$total_assists</td>
											     <td $align>$total_goals</td>
											     <td $align>$total_score</td>
										    </tr>
										    ";
										
										    // Grab all the individual weekly statistics for each player
										    $child_query = 'SELECT WEEK, GOALS, ASSISTS, SAVES, SCORE FROM STATS WHERE PLAYER_ID = ' . $player_id;
										    $child_result = do_query($child_query, $g_db_name, $g_username);
										    $j = 0;

										    // Cycle through all the weekly stats for an individual player and make them children rows
										    // of the parent row
										    while ($child_row = mysql_fetch_assoc($child_result)) {
											    $j = $j + 1;
											    $week_saves = $child_row['SAVES'];
											    $week_assists = $child_row['ASSISTS'];
											    $week_goals = $child_row['GOALS'];
											    $week_score = $child_row['SCORE'];
											    echo "<tr class=$shade>
													    <td></td>
													    <td>Week $j</td>
													    <td $align>$week_saves</td>
													    <td $align>$week_assists</td>
													    <td $align>$week_goals</td>
													    <td $align>$week_score</td>
												     </tr>
											    ";
										    } 
										    $i = $i + 1;
									    }
                                    }
								?>
							</table>
					</div>
					<div id="fragment-3" class="ui-tabs-panel ui-tabs-hide">
						<table id="trade_table">
							<tr class="table_header">
								<td width=25></td>
								<td class="trade_cell">Pending</td>
								<td class="trade_cell"></td>
								<td class="trade_cell"></td>
								<td class="trade_cell"></td>
								<td class="trade_cell"></td>
							</tr>
                            
                            <?php
                            
                                $team_1    = array();
                                $team_2    = array();
                                $player_1  = array();
                                $player_2  = array();
                                $date      = array();
                                
                                //Query to get the current trades active for this team
                                $query = "SELECT *, UNIX_TIMESTAMP(PROPOSED_ON) AS time 
                                          FROM PEND_TRADE 
                                          WHERE (TEAM1 = $team_id OR TEAM2 = $team_id) AND STATUS = 'Pending'
                                          ORDER BY PROPOSED_ON";
                                $result = do_query($query, $g_db_name, $g_username);

                                //Check if there are any active tradings.  If there aren't any 
                                //let the team owner know that
                                if (mysql_num_rows($result) == 0){
                                    echo "<tr class='shade_odd'>
                                            <td></td>
                                            <td colspan=4>There are currently no pending trades for your team</td>
                                          </tr>";
                                }
                                else{
                                    while($row = mysql_fetch_array($result)){
                                        $trade_id[] = $row['PEND_TRADE_ID'];
                                        $team2_id[] = $row['TEAM2'];
                                        $team_1[]   = get_value("team_id",$row['TEAM1']);
                                        $team_2[]   = get_value("team_id",$row['TEAM2']);
                                        $player_1[] = get_value("player_id",$row['PLAYER1']);
                                        $player_2[] = get_value("player_id",$row['PLAYER2']);                                     
                                        $date[]     = date("m-j-Y", $row['time']);
                                    }
                                    
                                    //Output a row for each active trade.  Add the accept and decline buttons in this team
                                    //is team number 2 in the database entry, because that means that this trade was proposed
                                    //to this team member
                                    $shaded = true;
                                    $proposed_to_you = "";
                                    $proposed_by_you = "";
                                    
                                    for ($i = 0; $i < sizeof($team_1); $i++){
                                        $class = ($shaded) ? "shade_odd" : "shade_even";
                                        $shaded = !$shaded;
                                        $colspan = "colspan=3";
                                        $info = "<tr class=$class>
                                                 <td></td>
                                                 <td><span class='player_name'>{$player_1[$i]}</span> for
                                                            <span class='player_name'>{$player_2[$i]}</span></td>
                                                 <td>proposed by {$team_1[$i]}</td>
                                                 <td>on {$date[$i]}</td>";
                                        //Check if need to add accept/decline option
                                        if ($team_id == $team2_id[$i]){
                                            $proposed_to_you .= $info;
                                            $proposed_to_you .= "<td colspan=2 class='accept_cell'>
                                                                    <span id='accept_{$trade_id[$i]}' class='accept_link' 
                                                                        onclick='acceptTrade(this);'><a>Accept</a></span>/
                                                                    <span id='decline_{$trade_id[$i]}' class='decline_link' 
                                                                        onclick='declineTrade(this);'><a>Decline</a></span>
                                                                </td>";
                                        }
                                        else {
                                            $proposed_by_you .= $info;
                                            $proposed_by_you .= "<td colspan=2></td>";
                                        }
                                        $proposed_by_you .= "</tr>";
                                        $proposed_to_you .= "</tr>";
                                    }
                                    echo "$proposed_to_you";
                                    echo "$proposed_by_you";
                                }
                            ?>
                            <tr id = "previous" class="table_header">
								<td width=25></td>
								<td class="trade_cell">Previous</td>
								<td class="trade_cell"></td>
								<td class="trade_cell"></td>
								<td class="trade_cell"></td>
								<td class="trade_cell"></td>
							</tr>
                            
                            <?php
                            
                                $team_1    = array();
                                $team_2    = array();
                                $player_1  = array();
                                $player_2  = array();
                                $status    = array();
                                $date      = array();
                                
                                //Query to get the current trades active for this team
                                $query = "SELECT *, UNIX_TIMESTAMP(ACCEPTED_ON) AS time 
                                          FROM PEND_TRADE 
                                          WHERE (TEAM1 = $team_id OR TEAM2 = $team_id) AND 
                                                (STATUS = 'Accepted' OR STATUS = 'Declined')
                                          ORDER BY ACCEPTED_ON DESC";
                                $result = do_query($query, $g_db_name, $g_username);

                                //Check if there are any active tradings.  If there aren't any 
                                //let the team owner know that
                                if (mysql_num_rows($result) == 0){
                                    echo "<tr class='shade_odd'>
                                            <td></td>
                                            <td colspan=4>There are currently no previous trades for your team</td>
                                          </tr>";
                                }
                                else{
                                    while($row = mysql_fetch_array($result)){
                                        $team_1[]   = get_value("team_id",$row['TEAM1']);
                                        $team_2[]   = get_value("team_id",$row['TEAM2']);
                                        $player_1[] = get_value("player_id",$row['PLAYER1']);
                                        $player_2[] = get_value("player_id",$row['PLAYER2']); 
                                        $history[]  = $row['STATUS'];                                    
                                        $date[]     = date("m-j-Y", $row['time']);
                                    }
                                    
                                    //Output a row for each previous trade
                                    $shaded = true;
                                    
                                    for ($i = 0; $i < sizeof($team_1); $i++){
                                    
                                        $class = ($shaded) ? "shade_odd" : "shade_even";
                                        $shaded = !$shaded;
                                        $colspan = "colspan=3";
                                        
                                        echo    "<tr class=$class>
                                                     <td></td>
                                                     <td><span class='player_name'>{$player_1[$i]}</span> for
                                                                <span class='player_name'>{$player_2[$i]}</span></td>
                                                     <td colspan=2>{$history[$i]} on {$date[$i]}</td>
                                                     <td></td>
                                                 </tr>";
                                              
                                    }
                                }
                            ?>

						</table>
					</div>
				</div>
			</div><!--Close content-->

			<div id="sidebar">
				<div id="scoreboard">
					<p class="team_label" id="home_team_name"><?php echo $home_team_name; ?></p>
					<p class="team_label" id="away_team_name"><?php echo $opp_team_name; ?></p>
					<p id="week_text"> Week <span id='week_shown'><?php echo"$week"?></span></p>
					<div id="left_arrow" onClick="getLastGame();"></div>
					<div id="right_arrow" onClick="getNextGame();"></div>
					<div class="digit" id="home_1_digit"></div>
					<div class="digit" id="home_2_digit"></div>
					<div class="digit" id="home_3_digit"></div>
					<div class="digit" id="away_1_digit"></div>
					<div class="digit" id="away_2_digit"></div>
					<div class="digit" id="away_3_digit"></div>
				</div>
			</div>	
			
			<div id="footer">
			  <?php echo "$footer"; ?>
			</div>
		</div>
	</div>
</body>
<?php } ?>
</html>
